using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using ORS.OrderRobot.Cache;
using ORS.OrderRobot.Helper;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;
using ORS.OrderRobot.ServiceContracts.Dtos.Api;
using ORS.OrderRobot.ServiceContracts.ThridPartApi;

namespace ORS.OrderRobot.WebApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SystemManageController : ControllerBase
    {
        private readonly ISystemConfigService _systemConfigService;
        private readonly ICache _cache;
        private readonly IShoppingService _shoppingService;
        private readonly IFlightInfoService _flightInfoService;
        private readonly IAccountLoginService _accountLoginService;
        private readonly IHttpHelper _httpHelper;
        private readonly IThirdBasketService _thirdBasketService;
        private readonly IEnumerable<IBackgroundRepeatTasker> _backgroundRepeatTaskers;
        public SystemManageController(
            ISystemConfigService systemConfigService,
            ICache cache,
            IShoppingService shoppingService,
            IFlightInfoService flightInfoService,
            IAccountLoginService accountLoginService,
            IHttpHelper httpHelper,
            IThirdBasketService thirdBasketService,
            IEnumerable<IBackgroundRepeatTasker> backgroundRepeatTaskers)
        {
            _systemConfigService = systemConfigService;
            _cache = cache;
            _shoppingService = shoppingService;
            _flightInfoService = flightInfoService;
            _accountLoginService = accountLoginService;
            _httpHelper = httpHelper;
            _thirdBasketService = thirdBasketService;
            _backgroundRepeatTaskers = backgroundRepeatTaskers;
        }
        /// <summary>
        /// 取得系统配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("getConfig")]
        public async Task<SystemConfigDto?> GetSystemConfig()
        {
            var config = await _systemConfigService.GetConfigAsync();
            return config;
        }

        /// <summary>
        /// 设置系统配置
        /// </summary>
        [HttpPost("updateConfig")]
        public async Task SetSystemConfig([FromBody] SystemConfigDto configDto)
        {
            await _systemConfigService.SetConfigAsync(configDto);
        }
        /// <summary>
        ///  获取系统中所有的缓存
        /// </summary>
        /// <param name="cacheType">不传获取所有,1为登录用户,2为航班信息</param>
        /// <returns></returns>
        [HttpGet("getAllCaches")]
        public async Task<Dictionary<string, object>> GetAllCaches(int? cacheType)
        {
            string prefix = null;
            if (cacheType.HasValue)
            {
                switch (cacheType.Value)
                {
                    case 1:
                        prefix = Consts.CacheKey.AccountPrefix;
                        break;
                    case 2:
                        prefix = Consts.CacheKey.AllBoarding;
                        break;
                }
            }
            var cacheKeys = await _cache.GetAllKeysAsync(prefix);
            var dic = new Dictionary<string, object>();
            foreach (var key in cacheKeys)
            {
                var cacheValue = await _cache.GetAsync<object>(key);
                dic.Add(key, cacheValue);
            }
            return dic;
        }
        /// <summary>
        /// 移除订单缓存
        /// </summary>
        /// <param name="email"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        [HttpGet("removeOrderCache")]
        public async Task<Dictionary<string, object>> RemoveOrderCache(string email,string productId)
        {
            await _cache.RemoveAsync(Consts.CacheKey.GenAccountTodayOrderKey(email, productId));
            var newCache = await GetAllCaches(null);
            return newCache;
        }
        /// <summary>
        /// 批量登录
        /// </summary>
        /// <returns></returns>
        [HttpGet("batchLogin")]
        public async Task<List<string>> BatchLogin()
        {
            var emails = await _accountLoginService.AutoLoginAsync();
            return emails;
        }
        /// <summary>
        /// 获取用户的购物车
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        [HttpGet("getUserBasket")]
        public async Task<IActionResult> GetUserBasket(string email)
        {
            var loginedUserInfo = await _cache.GetAsync<LoginResultInfo>(Consts.CacheKey.GenAccountLoginKey(email));
            if(loginedUserInfo == null)
            {
                throw new Exception("请先登录");
            }
            var url = $"/customers/{loginedUserInfo.CustomerId}/baskets";
            var requestInfo = new RequestInfo
            {
                BearerToken = loginedUserInfo.Token,
            };
            var httpResult = await _httpHelper.SendAsync(url, HttpMethod.Get, requestInfo);
            var parsedData = JsonSerializer.Deserialize<JsonElement>(httpResult.Body);
            return Ok(new { HttpCode = httpResult.StatusCode, data = parsedData });
        }
        /// <summary>
        /// 查询用户当前购物车中的详细内容
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        [HttpGet("getBasketDetail")]
        public async Task<IActionResult> GetBasketDetail(string email)
        {
            var loginedUserInfo = await _cache.GetAsync<LoginResultInfo>(Consts.CacheKey.GenAccountLoginKey(email));
            if (loginedUserInfo == null)
            {
                throw new Exception("请先登录");
            }
            var url = $"/baskets/{loginedUserInfo.BasketId}";
            var requestInfo = new RequestInfo
            {
                BearerToken = loginedUserInfo.Token,
            };
            var httpResult = await _httpHelper.SendAsync(url, HttpMethod.Get, requestInfo);
            var parsedData = JsonSerializer.Deserialize<JsonElement>(httpResult.Body);
            return Ok(new { HttpCode = httpResult.StatusCode, data = parsedData});
        }
        /// <summary>
        /// 手动下单模式
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("shopping")]
        public async Task Shopping(ShoppingInput input)
        {
            await _shoppingService.ShoppingAsync(input);
        }
        /// <summary>
        /// 哨兵模式下单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("guardShopping")]
        public async Task GuardShopping(ShoppingInput input)
        {
            await _shoppingService.TryAddBasket(input);
        }
        /// <summary>
        ///  设置下单依赖信息(需要手动调用登录)
        /// </summary>
        /// <returns></returns>
        [HttpPost("setShoppingDepInfo")]
        public async Task SetShoppingDepInfo()
        {
            var userList = await _accountLoginService.GetLoginedAccounts();
            if (userList == null || !userList.Any())
            {
                throw new Exception("无已登录用户");
            }
            var tasks = userList.Select(async email =>
            {
                await _shoppingService.SetShoppingDepInfoAsync(email);
            });
            await Task.WhenAll(tasks);
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="email"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("cacelOrder")]
        public async Task cancelOrder(string email,string orderNo)
        {
            var loginedUserInfo = await _cache.GetAsync<LoginResultInfo>(Consts.CacheKey.GenAccountLoginKey(email));
            if (loginedUserInfo == null)
            {
                throw new Exception("请先登录");
            }
            await _thirdBasketService.CancelOrder(orderNo, new CommonInput { BasketId = loginedUserInfo.BasketId, Email = loginedUserInfo.Email, Token = loginedUserInfo.Token });
        }
        /// <summary>
        /// 获取航班信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("getFlightInfos")]
        public async Task<List<FlightInfoDto>> GetFlightInfos(GetAirlineInput input)
        {
            var data = await _flightInfoService.GetList(input);
            return data;
        }
        /// <summary>
        /// 从服务器同步航班信息到本地数据库
        /// </summary>
        /// <returns></returns>
        [HttpGet("syncFlightInfoFromRemote")]
        public async Task SyncFlightInfo()
        {
            await _flightInfoService.SyncFromRemote();
        }
        /// <summary>
        /// 启动后台任务
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("startTasker")]
        public Task<IActionResult> StartTasker(string key)
        {
            var tasker = _backgroundRepeatTaskers.FirstOrDefault(i=>i.Key == key);
            if(tasker == null){
                throw new Exception($"{key}任务不存在");
            }
            tasker.StartAsync();
            return Task.FromResult<IActionResult>(Ok("已触发"));
        }
        /// <summary>
        /// 暂停后台任务
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("pauseTasker")]
        public async Task PauseTasker(string key)
        {
            var tasker = _backgroundRepeatTaskers.FirstOrDefault(i=>i.Key == key);
            if(tasker == null){
                throw new Exception($"{key}任务不存在");
            }
            await tasker.PauseAsync();
        }
        [HttpGet("resumeTasker")]
        public async Task ResumeTasker(string key)
        {
            var tasker = _backgroundRepeatTaskers.FirstOrDefault(i => i.Key == key);
            if (tasker == null)
            {
                throw new Exception($"{key}任务不存在");
            }
            await tasker.ResumeAsync();
        }
        /// <summary>
        /// 停止后台任务
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("stopTasker")]
        public async Task StopTasker(string key)
        {
            var tasker = _backgroundRepeatTaskers.FirstOrDefault(i=>i.Key == key);
            if(tasker == null){
                throw new Exception($"{key}任务不存在");
            }
            await tasker.StopAsync();
        }
        /// <summary>
        /// 获取任务状态
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("getTaskerState")]
        public IActionResult GetTaskerState(string key)
        {
            var tasker = _backgroundRepeatTaskers.FirstOrDefault(i => i.Key == key);
            if (tasker == null)
            {
                throw new Exception($"{key}任务不存在");
            }
            var state = tasker.TaskInfo;
            return Ok(new
            {
                state.Id,
                State = EnumHelper.GetEnumDescription(state.Status)
            });
        }
    }
} 